package com.chunxiadong.aspect;

import com.chunxiadong.MyblogApplication;
import com.chunxiadong.pojo.RequestLog;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @auther QiuShangcheng
 * @create 2021/6/5
 */
@Aspect
@Component
public class LogsAspect {
    private final Logger log = Logger.getLogger(this.getClass());
    //    切入点
    @Pointcut("execution(* com.chunxiadong.controller.*.*(..))")
    public void log(){}

    //方法执行前
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURI();
        String ip = request.getRemoteAddr();
//        String ip = request.getLocalAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
        log.info("请求参数：Result : {"+requestLog+"}");
    }

    //方法执行之后
    @After("log()")
    public void doAfter(){
//        log.info("-----doAfter---------------");
    }

    //方法返回之后
    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterReturn(Object result){
        log.info("返回参数：Result : {"+result+"}");
    }
}
